package com.ruoyi.web.controller.app.api.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.applet.appletUser.domain.AppletUser;
import com.ruoyi.applet.appletUser.service.IAppletUserService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.config.ServerConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.web.controller.app.config.WxConfig;
import com.ruoyi.web.controller.app.util.TokenUtil;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 用户接口
 * @Author: TangYuan
 * @Date: 2024/7/30 13:58
 */
@RestController
@RequestMapping("/wxApi/user")
public class UserAppletController extends BaseController {
    
    @Resource
    private IAppletUserService appletUserService;
    @Resource
    private ServerConfig serverConfig;
    
    /**
     * 登录时获取的 code（微信官方提供的临时凭证）
     */
    @PostMapping("/wxLogin")
    public AjaxResult wxLogin(@RequestBody JSONObject object) {
        // 微信官方提供的微信小程序登录授权时使用的URL地址
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        
        // 拼接需要的参数
        // appid = AppID 你自己的微信小程序APPID
        // js_code = AppSecret 你自己的微信APP密钥
        // grant_type=authorization_code = code 微信官方提供的临时凭证
        String params = String.format("appid=%s&secret=%s&js_code=%s&grant_type=authorization_code", WxConfig.getAppId(), WxConfig.getAppSecret(), object.get("code"));
        // 开始发起网络请求,若依管理系统自带网络请求工具，直接使用即可
        String res = HttpUtils.sendGet(url, params);
        JSONObject jsonObject = JSON.parseObject(res);
        String openid = (String) jsonObject.get("openid");
        if (StringUtils.isEmpty(openid)) {
            return AjaxResult.error("未获取到openid");
        }
        
        // 先通过openid来查询是否存在
        AppletUser appletUser = appletUserService.selectAppletUserByOpenid(openid);
        if (appletUser == null) {
            // 如果不存在就插入到我们的数据库里
            AppletUser wxUser = new AppletUser();
            wxUser.setOpenid(openid);
            wxUser.setNickname("微信用户");
            wxUser.setAvatar(WxConfig.getAvatar());
            wxUser.setCreateTime(DateUtils.getNowDate());
            wxUser.setBcStatus(1);
            appletUserService.insertAppletUser(wxUser);
            return AjaxResult.success(wxUser);
        } else {
            // 返回结果集到前段
            return AjaxResult.success(appletUser);
        }
    }
    
    /**
     * 上传头像文件
     */
    @PostMapping("/upload")
    public AjaxResult uploadFile(MultipartFile file) {
        try {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath() + "/applet/avatar";
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            url = url.replace("http:", "https:");
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }
    
    /**
     * 修改用户信息
     */
    @PostMapping("/updateUserInfo")
    public AjaxResult updateUserInfo(@RequestBody AppletUser appletUser) {
        String phone = appletUser.getPhone();
        if (StringUtils.isNotEmpty(phone)) {
            appletUser.setBcStatus(2);
        }
        int i = appletUserService.updateAppletUser(appletUser);
        return AjaxResult.success(i);
    }
    
    /**
     * 获取手机号
     */
    @PostMapping("/getPhoneNumber")
    @Log(title = "获取手机号", businessType = BusinessType.OTHER)
    public AjaxResult getPhoneNumber(@RequestBody Map<String, Object> data) {
        String appletToken = TokenUtil.getAppletToken();
        // 通过token和code来获取用户手机号
        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + appletToken;
        
        // 封装请求体
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("code", data.get("code").toString());
        
        // 封装请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Map<String, String>> httpEntity = new HttpEntity<>(paramMap, headers);
        
        // 通过RestTemplate发送请求，获取到用户手机号码
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<Object> response = restTemplate.postForEntity(url, httpEntity, Object.class);
        
        String body = String.valueOf(response.getBody());// 解析JSON字符串
        // 定义一个正则表达式来匹配 phoneNumber
        Pattern pattern = Pattern.compile("phoneNumber=(\\d+)");
        Matcher matcher = pattern.matcher(body);
        if (matcher.find()) {
            String phoneNumber = matcher.group(1); // 获取括号中的数字
            return AjaxResult.success("获取成功", phoneNumber);
        } else {
            return AjaxResult.error("手机号获取失败！");
        }
    }
    
    /**
     * 获取用户信息
     */
    @PostMapping("/getUserInfo")
    @Log(title = "获取用户信息", businessType = BusinessType.INSERT)
    public AjaxResult getUserInfo(@RequestBody AppletUser appletUser) {
        if (appletUser.getId() == null) {
            return AjaxResult.error("用户ID不能为空");
        }
        appletUser = appletUserService.selectAppletUserById(appletUser.getId());
        appletUser.setOpenid("");
        return AjaxResult.success(appletUser);
    }
}
